// import Nevow.Athena

innerspace.ClientConnector = Nevow.Athena.Widget.subclass('innerspace.ClientConnector');

innerspace.ClientConnector.methods(
	function parse(self, text){
		self.callRemote('parse', text);
		var actions = $('actions');
		actions.innerHTML += '<br/><span class="issued-command">' + text + '</span>';
	},
	function setObservations(self, observations){
		document.getElementById('obj-name').innerHTML = observations['name'];
		document.getElementById('obj-description').innerHTML = observations['description'];
		
		var contents_area = $('contents-area');
		var output = '<ul id="contents-list">';
		output += '<li onClick="look(&quot;here&quot;)"><hr height="20"/></li>';
		for(key in observations['contents']){
			output += '<li onClick="look(this.innerHTML)">' + observations['contents'][key] + '</li>';
		}
		output += '</ul>';
		contents_area.innerHTML = output;
	},
	function write(self, text){
		var actions = $('actions');
		actions.innerHTML += '<br/>' + text;
		setTimeout(function(){
			actions.scrollTop = actions.scrollHeight - actions.style.height;
		}, 500);
	},
	function objedit(self, info){
		return openEditor('entity', info, 435, 390);
	},
	function verbedit(self, info){
		return openEditor('verb', info, 821, 551);
	},
	function propedit(self, info){
		return openEditor('property', info, 821, 551);
	},
	function acledit(self, info){
		return openEditor('acl', info, 435, 390);
	}
);

function openEditor(type, info, width, height){
	var resultDeferred = new Divmod.Defer.Deferred();
	
	var editorID = setInterval(function(){
		var window_name = type + '-' + info['origin'] + '-' + info['id'] + '-' + Date.now();
		var editorWindow = window.open('/edit/' + type, window_name, 'location=0,status=0,scrollbars=0,resizable=1,width=' + width + ',height=' + height);
		editorWindow.info = info;
		editorWindow.resultDeferred = resultDeferred;
		editorWindow.clientWindow = window;
		
		var spyID = setInterval(function(){
			if(editorWindow.closed && ! resultDeferred._called){
				resultDeferred.callback(null);
				clearInterval(spyID);
			}
		}, 100);
		
		clearInterval(editorID);
	}, 100);
	
	return resultDeferred;
}

function getConnector(){
	return Nevow.Athena.Widget.get($('athenaid:1-client-connector'));
}

function handleKeyEvent(event){
	if(event.which == 13){
		var connector = getConnector();
		if(event.target.value){
			connector.parse(event.target.value);
		}
		event.target.value = '';
	}
}

function look(item){
	var connector = getConnector()
	connector.parse('look ' + item);
}
